package com.accp.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.accp.wxmp.service.CoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


import me.chanjar.weixin.common.util.StringUtils;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutTextMessage;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/weixin")
public class WeiXinController {
    Logger logger= LoggerFactory.getLogger(WeiXinController.class);
	@Autowired
	protected WxMpConfigStorage configStorage;
	@Autowired
	protected WxMpService wxMpService;
	@Autowired
	protected CoreService coreService;
	   /**
     * 微信公众号webservice主服务接口，提供与微信服务器的信息交互
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/portal",method = RequestMethod.GET)
    public void wechatCore(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("进入了portal");
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);

        String signature = request.getParameter("signature");
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        logger.info("signature="+signature+"nonce="+nonce+"timestamp="+timestamp);
        if (!this.wxMpService.checkSignature(timestamp, nonce, signature)) {
            logger.info("非法请求");
            // 消息签名不正确，说明不是公众平台发过来的消息
            response.getWriter().println("非法请求");
            return;
        }
        String token=request.getParameter("token");
        if (StringUtils.isNotBlank(token)) {
            logger.info("token="+token);
            // 说明是一个仅仅用来验证的请求，回显token
            String tokenOut = String.copyValueOf(token.toCharArray());
            response.getWriter().println(tokenOut);
            return;
        }
        String echoStr = request.getParameter("echostr");
        if (StringUtils.isNotBlank(echoStr)) {
            logger.info("echoStr="+echoStr);
            // 说明是一个仅仅用来验证的请求，回显echostr
            String echoStrOut = String.copyValueOf(echoStr.toCharArray());
            response.getWriter().println(echoStrOut);
            return;
        }
        response.getWriter().println("不可识别的加密类型");
        return;
    }

    @RequestMapping(value = "/portal",method = RequestMethod.POST)
    public void wechatCore1(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("进入了portal");
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        String signature = request.getParameter("signature");
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        logger.info("signature="+signature+"nonce="+nonce+"timestamp="+timestamp);
        if (!this.wxMpService.checkSignature(timestamp, nonce, signature)) {
            logger.info("非法请求");
            // 消息签名不正确，说明不是公众平台发过来的消息
            response.getWriter().println("非法请求");
            return;
        }
        String encryptType = StringUtils.isBlank(request.getParameter("encrypt_type"))
                ? "raw"
                : request.getParameter("encrypt_type");

        if ("raw".equals(encryptType)) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
            WxMpXmlOutMessage outMessage = this.coreService.route(inMessage);
            PrintWriter out=response.getWriter();
            this.logger.info("明文传输的消息"+inMessage.toString());
            out.print(outMessage.toXml());
            out.flush();
            return;
        }
        if ("aes".equals(encryptType)) {
            // 是aes加密的消息
            String msgSignature = request.getParameter("msg_signature");
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(
                    request.getInputStream(), this.configStorage, timestamp, nonce,
                    msgSignature);
            System.out.println(String.format("\n消息解密后内容为：\n{} ", inMessage.toString()));
            WxMpXmlOutMessage outMessage = this.coreService.route(inMessage);
            System.out.println(response.toString());
            response.getWriter()
                    .write(outMessage.toEncryptedXml(this.configStorage));
            return;
        }
    }
}
